import * as vscode from 'vscode';
import { UtilityItem } from './items/utility_item';

import { UtilityQuery } from '../gitlab/utility_query';
import { ItemModel } from './items/item_model';
import { UTILITIES, CONFIG_NAMESPACE } from '../constants';
import { extensionState } from '../extension_state';
import { gitExtensionWrapper } from '../git/git_extension_wrapper';
import { WrappedRepository } from '../git/wrapped_repository';

async function getAllGitlabRepositories(): Promise<WrappedRepository[]> {
  const projectsWithUri = gitExtensionWrapper.repositories.map(async repository => {
    await repository.getProject(); // make sure we tried to fetch the project
    return repository;
  });

  return Promise.all(projectsWithUri);
}

export class DataProvider implements vscode.TreeDataProvider<ItemModel | vscode.TreeItem> {
  private eventEmitter = new vscode.EventEmitter<void>();

  private children: UtilityItem[] = [];

  onDidChangeTreeData = this.eventEmitter.event;

  constructor() {
    extensionState.onDidChangeValid(this.refresh, this);
  }

  async getChildren(el: ItemModel | undefined): Promise<UtilityItem[] | ItemModel[] | vscode.TreeItem[]> {
    if (el) return el.getChildren();

    const customQueries =
      vscode.workspace
        .getConfiguration(CONFIG_NAMESPACE)
        .get<UtilityQuery[]>(UTILITIES) || [];
    this.children = customQueries.map(q => new UtilityItem(q.name, q.type));
    return this.children;
  }

  // eslint-disable-next-line class-methods-use-this
  getParent(): null {
    return null;
  }

  // eslint-disable-next-line class-methods-use-this
  getTreeItem(item: vscode.TreeItem | ItemModel) {
    if (item instanceof ItemModel) return item.getTreeItem();
    return item;
  }

  refresh(): void {
    this.eventEmitter.fire();
  }
}
